<template>
  <div class="container">
    <div class="navigationBar" style="width: 98%;margin: 10px auto 0">
      <el-row :gutter="24">
        <!-- 搜索框 -->
        <el-col :span="5">
          <el-input v-model="listQuery.name" placeholder="请输入店铺名称" clearable @change="search"></el-input>
        </el-col>
        <el-col  :span="16">
          <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        </el-col>

        <el-col :span="3" align="center" class="add-store">
          <el-button type="success" @click="handleAdd">新增店铺</el-button>
        </el-col>

      </el-row>
    </div>

    <div class="filter-container">
      <el-checkbox v-model="formThead.name" label="店铺名称">店铺名称</el-checkbox>
      <el-checkbox v-model="formThead.customer_id" label="所属用户">所属用户</el-checkbox>
      <el-checkbox v-model="formThead.member" label="会员">会员</el-checkbox>
<!--      <el-checkbox v-model="formThead.province" label="所属省份">所属省份</el-checkbox>-->
<!--      <el-checkbox v-model="formThead.city" label="所属城市">所属城市</el-checkbox>-->
<!--      <el-checkbox v-model="formThead.country" label="所属县/区">所属县/区</el-checkbox>-->
      <el-checkbox v-model="formThead.address" label="详细地址">详细地址</el-checkbox>
      <el-checkbox v-model="formThead.contact" label="联系人">联系人</el-checkbox>
      <el-checkbox v-model="formThead.telephone" label="联系电话">联系电话</el-checkbox>
      <el-checkbox v-model="formThead.wechat_qrcode" label="联系人二维码">联系人二维码</el-checkbox>
      <el-checkbox v-model="formThead.expire_date" label="过期日期">过期日期</el-checkbox>
      <el-checkbox v-model="formThead.performance" label="店铺业绩">店铺业绩</el-checkbox>
      

    </div>

    <el-table :data="storeList" class="table" border :key="storeList.length"
              v-loading="loading"
              element-loading-text="拼命加载中....">
      <el-table-column label="店铺名称" align="center" v-if="formThead.name">
        <template slot-scope="{row}">
          <span>{{row.name}}</span>
        </template>
      </el-table-column>

      <el-table-column label="所属用户" align="center" v-if="formThead.customer_id">
        <template slot-scope="{row}">
          <span>{{ getCustomerName(row.customer_id) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="会员" align="center" v-if="formThead.member">
        <template slot-scope="{row}">
          <span v-if="row.expire_date.length">会员</span>
          <span v-else>无</span>
        </template>
      </el-table-column>

<!--      <el-table-column label="所属省份" align="center" v-if="formThead.province">-->
<!--        <template slot-scope="{row}">-->
<!--          <span>{{getProvinceName(row.province)}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->

<!--      <el-table-column label="所属城市" align="center" v-if="formThead.city">-->
<!--        <template slot-scope="{row}">-->
<!--          <span>{{getCityName(row.city)}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->

<!--      <el-table-column label="所属县/区" align="center" v-if="formThead.country">-->
<!--        <template slot-scope="{row}">-->
<!--          <span>{{getCountryName(row.country)}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="详细地址" align="center" v-if="formThead.address">
        <template slot-scope="{row}">
          <span>{{ getAddress(row.province, row.city, row.country, row.address)}}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系人" align="center" v-if="formThead.contact">
        <template slot-scope="{row}">
          <span>{{row.contact}}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系电话" align="center" v-if="formThead.telephone">
        <template slot-scope="{row}">
          <span>{{row.telephone}}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系人微信二维码" align="center" v-if="formThead.wechat_qrcode">
        <template slot-scope="{row}">
          <img :src="row.wechat_qrcode === ''? null: row.wechat_qrcode" alt="暂无二维码"
               @click="bigImage(row.wechat_qrcode)">
        </template>
      </el-table-column>

      <el-table-column label="过期日期" align="center" v-if="formThead.expire_date">
        <template slot-scope="{row}">
          <span>{{row.expire_date}}</span>
        </template>
      </el-table-column>

      <el-table-column label="店铺业绩" align="center" v-if="formThead.performance">
        <template slot-scope="{row}">
          <i class="el-icon-view" @click="showPerformance(row)"></i>
        </template>
      </el-table-column>

      <el-table-column label="机构图片" align="center">
        <template slot-scope="{row}">
          <img :src="row.store_img === ''? null: row.store_img" alt="暂无机构图片"
               @click="bigImage(row.store_img)">
        </template>
      </el-table-column>

      <el-table-column label="机构介绍" align="center">
        <template slot-scope="{row}">
          <span>{{row.store_introduction}}</span>
        </template>
      </el-table-column>

      <el-table-column label="机构logo" align="center">
        <template slot-scope="{row}">
          <img :src="row.store_logo === ''? null: row.store_logo" alt="暂无机构logo"
               @click="bigImage(row.store_logo)">
        </template>
      </el-table-column>
      
      <el-table-column label="培训科目" align="center">
        <template slot-scope="{row}">
          <span v-for="(subject,index) in row.subjects" :key="index">
            {{subject.name}}
          </span>
          <!-- <el-checkbox-group v-model="row.subject_id">
            <el-checkbox v-for="subject in subject" :label="subject_id" :key="subject.id" disabled>{{subject.name}}</el-checkbox>
          </el-checkbox-group> -->
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center"  width="230px">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleDetail(row)" style="margin: 0">详情</el-button>
<!--          <el-button size="mini" type="primary" @click="handleEdit(row)" style="margin: 0" v-if="false">编辑</el-button>-->
          <!-- 根据customer_id将用户删除 -->
          <el-button size="mini" type="danger" @click="openDelete(row.customer_store_id)" style="margin: 0">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

      <transition name="el-zoom-in-top">
        <div v-show="bigImageSrc !== null && bigImageSrc!==''" class="bigImg" @click="bigImage(null)">
          <img :src="bigImageSrc" style="width:auto; height:400px;border-radius:5px;">
        </div>
      </transition>

    <div class="pagination-container">
      <el-pagination :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>


    <add-store ref="showAddDialog"/>
    <edit-store ref="showEditDialog"/>
    <detail-bind-card ref="showDetailDialog"/>
    <store-performance ref="showStorePerformanceDialog"/>

  </div>
</template>

<script>

  import addStore from './add'
  import editStore from './edit'
  import detailBindCard from '../store/detail'
  import storePerformance from './storePerformance'

  import store from '@/store'
  import {list,del,getSubject,infoStore} from '@/api/thk/store'
  import {list as getCustomerList} from '@/api/thk/customer'
  import {list as getProvinceAndCityList} from '@/api/thk/city'
  import {list as getOrganizationList} from '@/api/thk/organization'
  import {getStorePerformance} from '@/api/thk/performance'



  export default {
    name: 'Store',
    components: {
      addStore,
      editStore,
      detailBindCard,
      storePerformance
    },
    data() {
      return {
        // save storeList field
        storeList: [],
        bigImageSrc: null,
        customerList: [],
        // provinceAndCityList: [],
        // cityList: [],
        // countryList: [],
        // organizationList: [],
        formThead: {
          name: true,
          customer_id: true,
          province: true,
          city: true,
          address: true,
          country: true,
          contact: true,
          telephone: true,
          wechat_qrcode: true,
          expire_date: false,
          performance: false,
          member:true,
          allpagesize:0
        },
        listQuery: {
          name: undefined,
          status:undefined,
          page: 1,
          pagesize: 10
        },
        total: undefined,
        loading: true,
        subject:[],
      }
    },

    // call api
    created() {
      this.getOrganizationList()
      this.getStoreList()
      this.getCustomerList()
      this.getProvinceAndCityList()
      this.getSubject()
      this.allpagesize=this.total
    },

    updated: function () {
      this.$nextTick(function () {
        this.loading = false
      })
    },

    methods: {
      // 获取店铺列表
      getStoreList(){
        console.log(this.listQuery,"listQuery")
        list(store.getters.token, this.listQuery).then(res =>{
          this.total = res.data.list.total
          this.storeList = res.data.list.data
          console.log(">>>>> storeList")
          console.log(this.storeList,"11111111111111111111111111111")
        },error => {
          console.log(error)
        })
      },

      // 弹出增加对话框
      handleAdd(){
        // 传递，customerList和provinceAndCityList用于选择所属用于和所属城市
        this.$refs.showAddDialog.cancelSubmit(this.customerList,this.provinceAndCityList,this.organizationList,this.subject)
      },

      // 编辑店铺，row为回显的数据
      handleEdit(row){
        console.log(this.provinceAndCityList)
        this.$refs.showEditDialog.showEditDialog(row,this.customerList,this.provinceAndCityList, this.organizationList)
      },

      // 删除店铺方法
      handleDelete(customer_store_id){
        del(store.getters.token, customer_store_id)
        this.getStoreList()
      },

      handleDetail(row){
        
        let storeList=[]
        let allstore_id=[]
        // console.log(row.team_customer_store_id.length)
        if(row.team_customer_store_id!=null){
          allstore_id=row.team_customer_store_id.split(',')
        }else if(row.team_customer_store_id!=null&&row.team_customer_store_id.length>1){
          allstore_id.push(row.team_customer_store_id)
        }else{
          this.$refs.showDetailDialog.showDetailDialog(row,storeList,this.customerList, this.provinceAndCityList, this.organizationList,this.subject)
          return;
        }
        console.log("123")
        console.log(row.team_customer_store_id)
        // /store/index/infoStore
        allstore_id.map((item,index)=>{
          infoStore({token:store.getters.token,customer_store_id:item}).then(res=>{
            console.log(res.data.data)
            storeList.push(res.data.data)
            console.log(storeList.length==allstore_id.length)
            if(storeList.length==allstore_id.length){
              this.$refs.showDetailDialog.showDetailDialog(row,storeList,this.customerList, this.provinceAndCityList, this.organizationList,this.subject)
            }
          })
        })
        console.log(storeList,"789")
        // this.$refs.showDetailDialog.showDetailDialog(row,storeList,this.customerList, this.provinceAndCityList, this.organizationList,this.subject)
        // list(store.getters.token,{page:1,pagesize:10000}).then(res =>{
        //   console.log(">>>>> storeList",res)
        //   res.data.list.data.filter(res=>{

        //     for(let i=0;i<allstore_id.length;i++){
        //       console.log(res.customer_store_id,allstore_id[i])
        //       if(res.customer_store_id==Number(allstore_id[i])){
        //         console.log("11111111111111111111111111111")
        //         storeList.push(res)
        //         console.log(storeList)
        //       }
        //     }
        //   })
        //   this.$refs.showDetailDialog.showDetailDialog(row,storeList,this.customerList, this.provinceAndCityList, this.organizationList,this.subject)
        // },error => {
        //   console.log(error)
        // })
        // if(row.account.length!=0||row.name!=null){
        //   console.log("我进来了")
        //   this.$refs.showDetailDialog.showDetailDialog(row,this.customerList, this.provinceAndCityList, this.organizationList,this.subject)
        // }else if(row.province==null||row.name==null){
        //   this.$message({
        //     showClose: true,
        //     message: '该店铺未填写店铺信息',
        //     type: 'error'
        //   });
        // }else{
        //   this.$message({
        //     showClose: true,
        //     message: '该店铺未绑卡',
        //     type: 'error'
        //   });
        // }
      },

      // 删除店铺操作
      // 弹出是否删除对话框, then中调用handleDelete
      openDelete(customer_store_id) {
        this.$confirm('此操作将会删除店铺, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleDelete(customer_store_id)
          this.$message({
            type: 'success',
            message: '删除成功!'

          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 获取用户列表
      getCustomerList(){
        getCustomerList(store.getters.token,{pagesize:1000000}).then(res=>{
          this.customerList = res.data.list.data
        }).then(err => {
          console.log(err)
        })
      },

      // 获取organization数据
      getOrganizationList(){
        getOrganizationList(store.getters.token).then(res => {
          this.organizationList = res.data.list.data
        }).catch(err => {
          console.log(err)
        })
      },
      getSubject(){
        getSubject(store.getters.token).then(res=>{
          this.subject=res.data.data
        }).catch(err=>{
          this.$message({
            type:'error',
            message:'err.data.msg'
          })
        })
      },
      // 根据用户id返回用户名,用于显示店铺所属用户
      getCustomerName(customer_id){
        let customer = this.customerList.find(customer => {
          return customer.customer_id == customer_id
        })

        if(customer){
          return customer.nickname
        }

        return ''

      },

      // 获取省市数据
      getProvinceAndCityList(){
        getProvinceAndCityList(store.getters.token).then(res => {
          console.log('===== getProvinceList =====')

          this.provinceAndCityList = res.data.list
          // 获取全部数据的时候,将city的数据筛选出来
          this.getCityList()

          console.log(this.provinceAndCityList)
        }).catch(err => {
          console.log(err)
        })
      },

      // 获取city数据数据
      getCityList(){
        let citys = []
        for(let province of this.provinceAndCityList){
          citys.push(...province.children)
        }

        this.cityList = citys
        this.getCountryList()
      },

      // 遍历获取所有contury中的数据
      getCountryList(){
        let countrys = []
        for(let city of this.cityList){
          countrys.push(...city.children)
        }
        this.countryList = countrys
        console.log(this.countryList)
      },

      // 根据省id返回省名称
      getProvinceName(id){
        let province = this.provinceAndCityList.find(province => {
          return province.province_id === id
        })

        if(province){
          return province.province
        }

        return ''
      },

      // 根据city id返回cityName
      getCityName(id){
        let city = this.cityList.find(city => {
          return id === city.city_id
        })
        if(city){
          return city.city
        }
        return ''
      },

      // 根据country_id返回countryName
      getCountryName(id){
        let country = this.countryList.find(country => {
          return id === country.country_id
        })
        if(country){
          return country.country
        }
        return ''
      },

      // 根据联系人id获取联系人的名称(联系人数据在organization中)
      getContactName(organization_id){

        let organizations = this.organizationList.filter(organization => {
          return organization.customer_organization_id == organization_id
        })

        if(organizations[0]){
          return organizations[0].contact
        }

        return ''

      },

      getAddress(province, city, country, address){
        let detailedAddress = ""
        if(province !== null && province !== ''){
          detailedAddress += (province.province)
        }

        return detailedAddress + (city !== null ? city.city : '') + (country !== null ? country.country : '') + address
      },


      // 搜索功能
      search(){
        this.listQuery.page = 1
        this.getStoreList()
      },

      handleSizeChange(val) {
        this.listQuery.pagesize = val
        this.getStoreList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.listQuery.pagesize=10
        this.getStoreList()
      },

      // 大图弹窗函数
      bigImage(src) {
        if (src!==null) {
          this.$set(this, 'bigImageSrc', src)
          console.log(this.bigImageSrc)
        } else {
          this.$set(this, 'bigImageSrc', null)
        }
      },

      showPerformance(row){
        // 发送请求获取活动业绩的数据
        getStorePerformance(store.getters.token, {store_id: row.store_id}).then(res => {
          this.$refs.showStorePerformanceDialog.showStorePerformance(res)
        }).catch(err => {
          this.$message("获取店铺业绩失败")
        })
      },
    },

    computed:{

    }
  }
</script>

<style scoped>
  img{
    height: 50px;
    width: 50px;
    margin: 0;
    padding: 0;
  }
  .filter-container{
    margin: 10px 0 0 20px;
  }
  .table{
    width: 98%;
    margin: 10px auto 0;
  }
  .add-store{
    position: relative;
    top: 35px;
  }
  .bigImg img{
    max-width: 600px;
    min-width: 150px;
    height:auto;
    border-radius:10px;
  }

  .bigImg {
    min-width: 100%;
    min-height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999999;
    background: rgba(0, 0, 0, .5);
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    /*transition:1s;*/
  }
  i::before{
    /*display: inline-block;*/
    font-size: 20px;
    height: 18px;
    width: 18px;
  }

  i:hover{
    color: #409EFF;
  }
</style>
